package com.nf.xiaomi.service.impl;

import com.nf.xiaomi.dao.ProductInfoDao;
import com.nf.xiaomi.dao.impl.ProductInfoDaoImpl;
import com.nf.xiaomi.entity.CartItemEntity;
import com.nf.xiaomi.entity.ProductEntity;
import com.nf.xiaomi.model.AttributeModel;
import com.nf.xiaomi.service.ShoppingCartService;
import com.nf.xiaomi.util.JsonUtils;
import com.nf.xiaomi.vo.CartItemVO;

import java.util.ArrayList;
import java.util.List;

public class ShoppingCartServiceImpl implements ShoppingCartService {
    private List<CartItemEntity> countAndSubtotal;

    @Override
    public int addItem(Long userAccount, int detailID, Integer amount, String proName) {
        Integer userID = USER_DAO.getAllID(userAccount);
        Integer cartID = SHOPPING_CART_DAO.getCartID(userID, detailID);
        if(cartID!=null){
            Integer daoAmount = SHOPPING_CART_DAO.getAmount(cartID);
            return SHOPPING_CART_DAO.setAmount(cartID, daoAmount+amount);
        }
        return SHOPPING_CART_DAO.addItem(userID,detailID,amount,proName);
    }

    @Override
    public List<CartItemVO> getUserCartItemList(Long userAccount) {
        Integer userID = USER_DAO.getAllID(userAccount);
        List<CartItemEntity> itemList = SHOPPING_CART_DAO.getUserCartItemList(userID);

        Integer[] ids = getDetailIds(itemList);
        ProductInfoDao infoDao=new ProductInfoDaoImpl();
        List<ProductEntity> attributeList = infoDao.getAttributeList(ids);

        ProductEntity removeAttribute=new ProductEntity();
        List<CartItemVO> cart=new ArrayList<>();
        for (CartItemEntity cartItem : itemList) {
            CartItemVO vo=new CartItemVO(cartItem);
            Integer detailID = cartItem.getDetailID();
            for (ProductEntity attribute : attributeList) {
                if(attribute.getProductDetailID()==detailID){
                    AttributeModel model = JsonUtils.readValue(attribute.getAttributeList(),
                            AttributeModel.class);
                    vo.setDesc(model.getMemory()+" "+model.getColor());
                    vo.setPrice(attribute.getProductDetailPrice());
                    removeAttribute=attribute;
                    break;
                }
            }
            attributeList.remove(removeAttribute);
            cart.add(vo);
        }
        return cart;

    }

    @Override
    public List<CartItemEntity> getCountAndSubtotal(Long userAccount) {
        Integer userID = USER_DAO.getAllID(userAccount);
        return SHOPPING_CART_DAO.getCountAndSubtotal(userID);
    }

    @Override
    public int delItem(int itemID) {
        return SHOPPING_CART_DAO.delItem(itemID);
    }

    @Override
    public int setAmount(int cartID, int amount) {
        Integer cartAmount = SHOPPING_CART_DAO.getAmount(cartID);
        if(cartAmount==1 && amount<0){
            return SHOPPING_CART_DAO.setAmount(cartID,cartAmount);
        }
        return SHOPPING_CART_DAO.setAmount(cartID,amount+cartAmount);
    }
}
